<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 添加角色 -->
      <el-button type="primary" @click="addOrEditDialogFormVisible = true"
        >添加角色</el-button
      >
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级 -->
            <el-row
              :class="[i1 === 0 ? 'bdtop' : '', 'bdbottom', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row.id, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级 -->
                <el-row
                  :class="[i2 !== 0 ? 'bdtop' : '', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      @close="removeRightById(scope.row.id, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row.id, item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              Role
              size="mini"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="open(scope.row.id)"
              >删除</el-button
            >
            <el-button
              @click="showSetRightDialog(scope.row)"
              type="warning"
              icon="el-icon-setting"
              size="mini"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      :title="isAddRole ? '添加角色' : '修改角色'"
      :visible.sync="addOrEditDialogFormVisible"
      @close="addDialogClosed"
    >
      <el-form :model="form" :rules="rules" label-width="80px" ref="formRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addOrEditDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEditRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      e
      :visible.sync="rightsEditDialogFormVisible"
      @close="rightsDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="roleRights"
        default-expand-all
        ref="treeRef"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rightsEditDialogFormVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="editRoleRights">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      type: 'tree',
      // 默认选中权限
      roleRights: [],
      rolesList: [],
      addOrEditDialogFormVisible: false,
      rightsEditDialogFormVisible: false,
      isAddRole: true,
      roleId: '',
      form: {
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {},
  created() {
    this.getRolesList()
  },
  methods: {
    // 角色授权
    async editRoleRights() {
      const rids = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const ridsStr = rids.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: ridsStr }
      )
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.getRolesList()
      this.$msg.success(res.meta.msg)
      this.rightsEditDialogFormVisible = false
    },
    // 关闭时清空
    rightsDialogClosed() {
      this.roleRights = []
    },
    async showSetRightDialog(role) {
      // 获取所有权限列表
      const { data: res } = await this.$http.get(`rights/${this.type}`)

      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.rightsList = res.data
      this.roleId = role.id
      // 递归获取三级节点的Id
      this.getLeafKeys(role, this.roleRights)
      this.rightsEditDialogFormVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    async removeRightById(roleId, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$msg.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        'roles/' + roleId + '/rights/' + rightId
      )
      if (res.meta.status !== 200) {
        // console.log(res)
        return this.$msg.error('删除角色指定权限失败')
      }
      this.$msg.success('删除角色指定权限成功')
      this.getRolesList()
    },
    open(uid) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // console.log(uid)
          const { data: res } = await this.$http.delete('roles/' + uid)
          if (res.meta.status !== 200) {
            // console.log(res)
            return this.$msg.error('删除角色失败')
          }
          this.$msg.success('删除角色成功')
          this.getRolesList()
        })
        .catch(() => {
          this.$msg.info('已取消删除')
        })
    },
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.rolesList = res.data
    },
    // 点击编辑按钮
    editRole(roleInfo) {
      this.isAddRole = false
      this.roleId = roleInfo.roleId
      this.form.roleName = roleInfo.roleName
      this.form.roleDesc = roleInfo.roleDesc
      this.addOrEditDialogFormVisible = true
    },
    // 添加或编辑角色
    addOrEditRole() {
      this.isAddRole = true
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return
        let meta = ''
        if (this.isAddRole) {
          // 添加角色
          // console.log(this.form)
          const { data: res } = await this.$http.post('roles', this.form)
          meta = res.meta
        } else {
          // 编辑角色
          const { data: res } = await this.$http.put(
            `roles/${this.roleId}`,
            this.form
          )
          meta = res.meta
        }
        if (meta.status !== 201) return this.$msg.error(meta.msg)
        this.$msg.success(meta.msg)
        this.addOrEditDialogFormVisible = false
        this.getRolesList()
      })
    },
    addDialogClosed() {
      // console.log(this)
      this.$refs.formRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
